package com.huimark.jaxws;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.lang.reflect.Field;
import java.util.List;

import com.sun.xml.ws.transport.http.servlet.ServletAdapter;
import com.sun.xml.ws.transport.http.servlet.WSServlet;

/**
 * SpringBeanAutowiringSupport,模拟它的逻辑，但是不行。因为adapter已经封装多次，不是最开始那个WebService类了
 * @author lenovo
 *
 */
public class WSSpringServlet extends WSServlet {

	private static final long serialVersionUID = -2601671022711147107L;

	@SuppressWarnings("unchecked")
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		com.sun.xml.ws.transport.http.servlet.WSServletDelegate wsd = this
				.getDelegate(servletConfig);
		try {
			Field field1 = wsd.getClass().getDeclaredField("adapters");
			field1.setAccessible(true);
			List<ServletAdapter> adapters = (List<ServletAdapter>) field1
					.get(wsd);
			//注入到spring中，使得service可以使用autowired注入spring对象
			for (ServletAdapter sad : adapters) {
				WSSpringServlet.processInjectionBasedOnServletContext(sad,
						getServletContext());
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public static void processInjectionBasedOnServletContext(Object target,
			ServletContext servletContext) {
		Assert.notNull(target, "Target object must not be null");
		WebApplicationContext cc = WebApplicationContextUtils
				.getRequiredWebApplicationContext(servletContext);
		AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
		bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
		bpp.processInjection(target);
	}
}
